package org.example.java_gobang.api;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.example.java_gobang.model.User;
import org.example.java_gobang.model.UserMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserAPI {

    @Resource
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        //根据username去数据库中查询  是否有匹配 的
        //如果找到匹配的  ,就说明登录成功
     User user =  userMapper.selectByName(username);
     System.out.println("[login] user=" + username);  //日志
     if (user == null || !user.getPassword().equals(password))  {
         //登录失败
         System.out.println("登录失败!");
         return new User();
     }
     HttpSession httpSession = req.getSession(true);  // 存在就返回 ,不存在就创建一个
     httpSession.setAttribute("user",user);
     return user;
    }

    //注册
    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        try {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        }catch (org.springframework.dao.DuplicateKeyException e) {  //出现重复的
             User user = new User();
             return user;
        }

    }
    //获取用户信息
    @GetMapping("/getUserInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        try {
            HttpSession httpSession = req.getSession(false);  //没有就返回空  有就返回
            User user = (User) httpSession.getAttribute("user");   //这里是拿到的不是数据库中的 最新数据 是登录那一刻的数据
            User newUser = userMapper.selectByName(user.getUsername());   //这才是数据库的最新更新的数据
            return newUser;
        }catch (NullPointerException e) {
            return new User();  //无效对象
        }

    }
}
